package org.xxforest.game.core.assets;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.PixmapIO;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.TextureData;
import com.badlogic.gdx.graphics.glutils.ETC1TextureData;
import com.badlogic.gdx.graphics.glutils.FileTextureData;

public class XXTextureAsyncLoader implements XXAsnycLoader {

	private TextureData textureData;
	private Texture texture ;
	
	private String fileName ;
	
	private XXTextureAsyncLoader(String fileName){
		this.fileName = fileName ;
	}
	
	public static XXTextureAsyncLoader create(String fileName){
		return new XXTextureAsyncLoader(fileName) ;
	}
	
	public void loadAsync () {
		Pixmap pixmap = null;
		Format format = null;
		boolean genMipMaps = false;
		
		FileHandle handle = Gdx.files.internal(fileName);
		if (!fileName.contains(".etc1")) {
			if (fileName.contains(".cim")){
				pixmap = PixmapIO.readCIM(handle);
			}
			else{
				pixmap = new Pixmap(handle);
			}
			textureData = new FileTextureData(handle, pixmap, format, genMipMaps);
		} else {
			textureData = new ETC1TextureData(handle, genMipMaps);
		}
	}
	
	public Texture getData () {
		if (texture != null) {
			texture.load(textureData);
		} else {
			texture = new Texture(textureData);
		}
		return texture;
	}

	public boolean isLoadFinish() {
		return textureData != null;
	}

	@Override
	public void dispose() {
		if(texture != null){
			texture.dispose() ;
			texture = null ;
		}
		if(textureData != null){
			textureData.disposePixmap() ;
			textureData = null ;
		}
	}

	@Override
	public String getFileName() {
		return this.fileName;
	}
	
}
